package com.eboss2.sbs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ChooseOptionAdapter;
import com.eboss2.sbs.adapter.CustomListAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.enums.EnumConsts;
import com.eboss2.sbs.model.CustomList;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyListView;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Date;
import java.util.List;

public class MyCustomFromManagerActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

	private PullToRefreshScrollView pullToRefreshScrollView;
	private MyListView listview;
	private List<CustomList> datas = new ArrayList<>();
	private CustomListAdapter adapter;
	private int page = 1;
	private int rows = Config.ROWS;

	private AlertDialog dialog_panel;

	private int TYPE_GRADE_OPTION = 1;
	private int TYPE_TIME_OPTION = 2;

	private final int REQUEST_CODE_QUERYDATE_FROM = 1;
	private final int REQUEST_CODE_QUERYDATE_TO = 2;

	private Date panel_dateFrom = new Date();
	private Date panel_dateTo = new Date();
	private Date query_dateFrom = panel_dateFrom;
	private Date query_dateTo = panel_dateTo;

	//等级选择
	private GridView gv_option_grade;
	private ArrayList<String> grade_values = new ArrayList<String>(){
		{
			add(EnumConsts.CustomGradeType.CustomType_0.getName());
			add(EnumConsts.CustomGradeType.CustomType_1.getName());
			add(EnumConsts.CustomGradeType.CustomType_2.getName());
			add(EnumConsts.CustomGradeType.CustomType_3.getName());
			add(EnumConsts.CustomGradeType.CustomType_4.getName());
			add(EnumConsts.CustomGradeType.CustomType_5.getName());
			add(EnumConsts.CustomGradeType.CustomType_6.getName());
		}
	};
	private BitSet grade_marks = new BitSet(grade_values.size());
	private ChooseOptionAdapter adapter_grade;
	private int gradeType = EnumConsts.CustomGradeType.CustomType_0.getCode();


	//日期选择
	private GridView gv_option_time;
	private ArrayList<String> time_values = new ArrayList<String>(){
		{
			add(EnumConsts.TimeZoneType.SEVENDAY.getName());
			add(EnumConsts.TimeZoneType.MONTH.getName());
			add(EnumConsts.TimeZoneType.MONTHLAST.getName());
			add(EnumConsts.TimeZoneType.CUSTOM.getName());
		}
	};
	private BitSet time_marks = new BitSet(time_values.size());
	private ChooseOptionAdapter adapter_time;
	private int timeType = EnumConsts.TimeZoneType.CUSTOM.getCode();
	private TextView tv_date_to, tv_date_from;
	private LinearLayout ly_time_zone;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_mycustom_from_manager);
		MyActivityManager.getInstance().addActivity(this);
		initView();
	}

	private void initView(){
		showView(R.id.titleback_btn_back, true);
		setTvText(R.id.tv_title, "发展会员列表");
		showView(R.id.next_sure, true);
		setTvText(R.id.next_sure, "筛选");
		textView(R.id.next_sure).setTextSize(13);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);


		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyCustomFromManagerActivity.MyOnRefreshListener());
		pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
		listview = (MyListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(this);

		for (int i = 0; i < 10; i++){
			CustomList customList = new CustomList();
			customList.setGrade("黄金等级");
			customList.setName("wcp"+i);
			customList.setCount(1);
			customList.setTime("2018-01-01");
			datas.add(customList);
		}


		adapter = new CustomListAdapter(this, datas);
		listview.setAdapter(adapter);

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		startActivity(new Intent(mContext, MyDetailCustomFromListActivity.class));
	}


	class MyOnRefreshListener implements PullToRefreshBase.OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
			String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			page++;
			getdata();
		}
	}


	private void refreshData(){
		datas.clear();
		page = 1;
		getdata();
	}

	private void getdata(){
//		Map<String, Object> params = new HashMap<String, Object>();
////		params.put("sid", mApp.getLoginEntity().getSid());
////		String key = getTvText(R.id.tv_search_key);
////		if(!StringUtil.isNull(key)){params.put("key", key);}
////		else{params.put("key", "");}
//		params.put("pagenum", page);
//		params.put("pagesize", rows);
//		API.http_post(this, API.COUPON_LIST, params, new HttpCallback<CouponListEntity>(this) {
//			@Override
//			public void onSuccess(int statusCode, CouponListEntity data) {
//				if(data!=null){
//					List<CouponEntity> tmp_datas = data.getCoupons();
//					if(tmp_datas==null||tmp_datas.size()==0||tmp_datas.size()<rows){
//						if(tmp_datas==null||tmp_datas.size()==0){
//							toast("没有更多数据");
//						}
//						pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
//					}
//					if(tmp_datas!=null&&tmp_datas.size()>0){
//						datas.addAll(tmp_datas);
//					}
//				}
//				boolean no_datas = (datas==null||datas.size()==0);
//				showView(R.id.eva_nodata, no_datas);
//				showView(R.id.listview, !no_datas);
//				adapter.notifyDataSetChanged();
//				pullToRefreshScrollView.onRefreshComplete();
//			}
//
//			@Override
//			public void onFailure(int code, String message) {
//				pullToRefreshScrollView.onRefreshComplete();
//				super.onFailure(code, message);
//
//			}
//
//			@SuppressWarnings({ "unchecked", "rawtypes" })
//			@Override
//			public TypeToken getTypeToken() {
//				return new TypeToken<CouponListEntity>() {
//				};
//			}
//		});
	}





	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.next_sure:
				showPanel();
				break;
			case R.id.tv_date_from:
//				intent.setClass(mContext, ChooseDateActivity.class);
//				String tmp_date_str_from = TimeUtil.getStringFromDate(panel_dateFrom==null?(new Date()):panel_dateFrom, ChooseDateActivity.FORMAT_DATE);
//				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_from);
//				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
//				intent.putExtra("toDate", TimeUtil.getStringFromDate(panel_dateTo, ChooseDateActivity.FORMAT_DATE));
//				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_FROM);
				DatePickDialog dialog = new DatePickDialog(this);
				//设置上下年分限制
				dialog.setYearLimt(5);
				//设置标题
				dialog.setTitle("选择时间");
				//设置类型
				dialog.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						panel_dateFrom = date;
						tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
					}
				});
				dialog.show();
				break;
			case R.id.tv_date_to:
//				intent.setClass(mContext, ChooseDateActivity.class);
//				String tmp_date_str_to = TimeUtil.getStringFromDate(panel_dateTo==null?(new Date()):panel_dateTo, ChooseDateActivity.FORMAT_DATE);
//				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_to);
//				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
//				intent.putExtra("fromDate", TimeUtil.getStringFromDate(panel_dateFrom, ChooseDateActivity.FORMAT_DATE));
//				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_TO);
				DatePickDialog dialog2 = new DatePickDialog(this);
				//设置上下年分限制
				dialog2.setYearLimt(5);
				//设置标题
				dialog2.setTitle("选择时间");
				//设置类型
				dialog2.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog2.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog2.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog2.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						panel_dateTo = date;//TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
						tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
					}
				});
				dialog2.show();
				break;
			case R.id.btn_filter_confirm:
				if(dialog_panel!=null){dialog_panel.dismiss();}

				if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
					query_dateFrom = panel_dateFrom;
					query_dateTo = panel_dateTo;
				}
				else{
					Date today = new Date();
					if(timeType== EnumConsts.TimeZoneType.SEVENDAY.getCode()){
						query_dateFrom = TimeUtil.getDateFromDate(today, -7);
						query_dateTo = TimeUtil.getDateFromDate(today, -1);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTH.getCode()){
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(today, 0);
					}
					else if(timeType== EnumConsts.TimeZoneType.MONTHLAST.getCode()){
						Date query_dateTo_tmp = TimeUtil.getDateFromString(TimeUtil.getCurrentDateString("yyyyMM")+"01", "yyyyMMdd");
						query_dateTo = TimeUtil.getDateFromDate(query_dateTo_tmp, -1);
						query_dateFrom = TimeUtil.getDateFromString(TimeUtil.getStringFromDate(query_dateTo, "yyyyMM")+"01", "yyyyMMdd");
					}
				}
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
				String to = TimeUtil.getStringFromDate(query_dateTo, "yyyy年MM月dd日");
				boolean checkshow = from.equals(to);
				showView(R.id.ly_date_chooser, checkshow?true:false);
				showView(R.id.ly_date_show, checkshow?false:true);
				setTvText(R.id.tv_date_choose, from);
				setTvText(R.id.tv_date_show, from+" - "+to);


				refreshData();
				break;
			default:break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return;
		switch (requestCode) {
			case REQUEST_CODE_QUERYDATE_FROM:
				String a = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateFrom = TimeUtil.getDateFromString(a, ChooseDateActivity.FORMAT_DATE);
				tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
				break;
			case REQUEST_CODE_QUERYDATE_TO:
				String b = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateTo = TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
				tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
				break;
			default: break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


	private void showPanel() {

		dialog_panel = new AlertDialog.Builder(mContext).create();
		dialog_panel.show();
		Window window = dialog_panel.getWindow();

		WindowManager.LayoutParams lp =window.getAttributes();
		lp.x=0;
		lp.y=150;

		// 设置布局
		window.setContentView(R.layout.dialog_coustom_from_list);
		// 设置宽高
		window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		// 设置弹出的动画效果
		// show at bottom
		window.setGravity(Gravity.TOP);

		ly_time_zone = (LinearLayout) window.findViewById(R.id.ly_time_zone);
		tv_date_from = (TextView) window.findViewById(R.id.tv_date_from);
		tv_date_to = (TextView) window.findViewById(R.id.tv_date_to);
		tv_date_from.setOnClickListener(this);
		tv_date_to.setOnClickListener(this);

		window.findViewById(R.id.btn_filter_confirm).setOnClickListener(this);

		gv_option_grade = (GridView) window.findViewById(R.id.gv_option_grade);
		adapter_grade = new ChooseOptionAdapter(mContext, grade_values, grade_marks);
		gv_option_grade.setAdapter(adapter_grade);
		gv_option_grade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_GRADE_OPTION, arg2);
			}
		});

		gv_option_time = (GridView) window.findViewById(R.id.gv_option_time);
		adapter_time = new ChooseOptionAdapter(mContext, time_values, time_marks);
		gv_option_time.setAdapter(adapter_time);
		gv_option_time.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_TIME_OPTION, arg2);
			}
		});

		reflashPanel();
	}


	private void adapterNotify(int adapterType, int index){
		if(adapterType==TYPE_GRADE_OPTION){
			gradeType = EnumConsts.CustomGradeType.getCodeByName(grade_values.get(index));
			reflashPanel();
		}
		else if(adapterType==TYPE_TIME_OPTION){
			timeType = EnumConsts.TimeZoneType.getCodeByName(time_values.get(index));
			reflashPanel();
		}
	}

	private void reflashPanel(){
		int size1 = grade_values.size();
		for (int i = 0; i < size1; i++) {
			int type_tmp = EnumConsts.CustomGradeType.getCodeByName(grade_values.get(i));
			grade_marks.set(i, type_tmp==gradeType?true:false);
		}

		int size2 = time_values.size();
		for (int i = 0; i < size2; i++) {
			int type_tmp = EnumConsts.TimeZoneType.getCodeByName(time_values.get(i));
			time_marks.set(i, type_tmp==timeType?true:false);
		}
		ly_time_zone.setVisibility(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()?View.VISIBLE:View.GONE);
		if(timeType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
			tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
			tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
		}

		adapter_grade.notifyDataSetChanged();
		adapter_time.notifyDataSetChanged();
	}

}
